import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * @author: zlz
 * @date: 2021/9/12 9:50
 * @description:
 * @since: JDK1.8
 */
public class NioDemo {
    private static List<SocketChannel> channelList = new ArrayList<SocketChannel>();
    public static void main(String[] args) throws IOException {
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
        serverSocketChannel.socket().bind(new InetSocketAddress(9000));
        // 设置为非阻塞
        serverSocketChannel.configureBlocking(false);
        System.out.println("服务启动成功");
        while (true) {
            // NIO的非阻塞是有操作系统内部实现的，调用了linux内核的accept函数
            SocketChannel channel = serverSocketChannel.accept();
            if (channel != null) {
                System.out.println("连接成功");
                channel.configureBlocking(false);
                channelList.add(channel);
            }
            // 遍历连接进行数据读取
            Iterator<SocketChannel> iterator = channelList.iterator();
            while (iterator.hasNext()) {
                SocketChannel socketChannel = iterator.next();
                ByteBuffer byteBuffer = ByteBuffer.allocate(128);
                int len = socketChannel.read(byteBuffer);
                if (len > 0) {
                    System.out.println("接收到消息：" + new String(byteBuffer.array()));
                } else if (len == -1) {
                    iterator.remove();
                    System.out.println("客户端断开连接！");
                }
            }
        }
    }
}
